package com.sxt.practiceapplication.pager;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.ColorInt;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.lzy.okhttputils.callback.StringCallback;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.qmuiteam.qmui.widget.popup.QMUIQuickAction;
import com.sxt.practiceapplication.R;
import com.sxt.practiceapplication.activities.StatisticActivity;
import com.sxt.practiceapplication.activities.course.CourseActivity;
import com.sxt.practiceapplication.adapter.StudyRecordListAdapter;
import com.sxt.practiceapplication.base.BasePager;
import com.sxt.practiceapplication.common.Constants;
import com.sxt.practiceapplication.common.ServerStatus;
import com.sxt.practiceapplication.common.Urls;
import com.sxt.practiceapplication.databinding.StudyRecordLayoutBinding;
import com.sxt.practiceapplication.entity.course.data.CourseItemData;
import com.sxt.practiceapplication.entity.studyrecord.StudyRecord;
import com.sxt.practiceapplication.entity.studyrecord.data.StudyRecordListData;
import com.sxt.practiceapplication.entity.user.LoginData;
import com.sxt.practiceapplication.utils.GsonBinder;
import com.sxt.practiceapplication.utils.LoginUser;
import com.sxt.practiceapplication.utils.ToastUtils;
import com.sxt.practiceapplication.utils.Tools;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class StudyPager extends BasePager {

    /**
     * 提示view
     */
    private TextView tip;

    /**
     * 学习记录数据
     */
    private List<StudyRecord> studyRecords;

    /**
     * 学习记录适配器
     */
    private StudyRecordListAdapter recordListAdapter;

    private StudyRecordLayoutBinding studyRecordBinding;
    private LoginData userData;

    public StudyPager(Context context) {
        super(context);
    }

    @Override
    protected void initContent(FrameLayout content) {

        tip = new TextView(context);
        tip.setGravity(Gravity.CENTER);

        studyRecordBinding = StudyRecordLayoutBinding.inflate(LayoutInflater.from(context));
        RecyclerView recyclerView = studyRecordBinding.studyRecord;
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        studyRecords = new ArrayList<>();
        recordListAdapter = new StudyRecordListAdapter(context, studyRecords);
        recordListAdapter.setOnItemClickListener(new StudyRecordListAdapter.ViewHolder.OnItemClickListener() {
            @Override
            public void onClick(View view, StudyRecord studyRecord) {
                StudyRecord.Course course = studyRecord.course;
                if (course == null) {
                    ToastUtils.show("未找到相关课程");
                    return;
                }
                OkHttpUtils.get(Urls.COURSE_URL + course.courseId + "/")
                        .tag(this)
                        .cacheMode(CacheMode.NO_CACHE)
                        .headers("Authorization", userData.getToken())
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String result, Call call, Response response) {
                                Intent intent = new Intent(context, CourseActivity.class);
                                CourseItemData courseItemData = GsonBinder.toObj(result, CourseItemData.class);
                                intent.putExtra("course", courseItemData.getData());
                                if (LoginUser.checkAndToLogin(context, intent)) {
                                    context.startActivity(intent);
                                }
                            }
                        });
            }

            @Override
            public void onLongClick(View view, StudyRecord studyRecord) {
                QMUIPopups.quickAction(context,
                        QMUIDisplayHelper.dp2px(context, 50),
                        QMUIDisplayHelper.dp2px(context, 30))
                        .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                        .shadow(true)
                        .skinManager(QMUISkinManager.defaultInstance(context))
                        .edgeProtection(QMUIDisplayHelper.dp2px(context, 20))
                        .addAction(new QMUIQuickAction.Action().text("删除").onClick(
                                (quickAction, action, position) -> {
                                    quickAction.dismiss();
                                    OkHttpUtils.delete(Urls.STUDY_RECORD_URL + studyRecord.id + "/")
                                            .tag(this)
                                            .cacheMode(CacheMode.NO_CACHE)
                                            .headers("Authorization", userData.getToken())
                                            .execute(new StringCallback() {
                                                @Override
                                                public void onSuccess(String s, Call call, Response response) {
                                                    Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                                                    queryStudyRecords();
                                                }
                                            });
                                }
                        ))
                        .show(view);
            }
        });
        recyclerView.setAdapter(recordListAdapter);
        content.addView(studyRecordBinding.getRoot());

        registerLoginStateChangeBroadcast();

        setOnMoreClickListener(view -> {
            Intent intent = new Intent(context, StatisticActivity.class);
            if (LoginUser.checkAndToLogin(context, intent)) {
                context.startActivity(intent);
            }
        });
    }

    @Override
    public void doInitData() {
        //设置标题
        headTitle.setText(R.string.study_title);
        //联网请求数据
        queryStudyRecords();
    }

    private void queryStudyRecords() {
        if (isLogin()) {
            userData = LoginUser.getCurrentUserData(context);
            OkHttpUtils.get(Urls.STUDY_RECORD_URL + "?user_id=" + userData.getUserId() + "&ordering=-id")
                    .tag(this)
                    .cacheMode(CacheMode.NO_CACHE)
                    .headers("Authorization", userData.getToken())
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String result, Call call, Response response) {
                            StudyRecordListData studyRecordListData = GsonBinder.toObj(result, StudyRecordListData.class);
                            if (studyRecordListData.getCode().equals(ServerStatus.SUCCESS.getCode())) {
                                studyRecords.clear();
                                studyRecords.addAll(studyRecordListData.getData().getResults());
                                if (!studyRecords.isEmpty()) {
                                    recordListAdapter.notifyDataSetChanged();
                                } else {
                                    showTip("暂无学习记录", Color.GRAY);
                                }
                            } else if (studyRecordListData.getCode().equals(ServerStatus.AUTH_ERROR.getCode())) {
                                Tools.showErrorDialog(context, studyRecordListData.getMessage());
                                LoginUser.logout(context);
                            }
                        }
                    });
        } else {
            showTip("请登录后查看", Color.RED);
        }
    }

    private boolean isLogin() {
        return LoginUser.isLogin(context);
    }

    private void showTip(String text, @ColorInt int colorRes) {
        tip.setTextColor(colorRes);
        tip.setText(text);
        content.removeAllViews();
        content.addView(tip);
    }

    private void registerLoginStateChangeBroadcast() {
        ((Activity) context).registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (isLogin()) {
                    queryStudyRecords();
                    content.removeAllViews();
                    content.addView(studyRecordBinding.getRoot());
                } else {
                    studyRecords.clear();
                    showTip("请登录后查看", Color.RED);
                }
            }
        }, new IntentFilter(Constants.LOGIN_STATE_CHANGE));
    }
}
